﻿using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ledict.ConditionExtract.Frm.NodeTree
{
    public partial class RuleShare : BaseForm
    {
        readonly TreeDataBLL trbll = new TreeDataBLL();
        private List<TreeNode> NodeList = new List<TreeNode>();//节点树上显示出来的所有节点集合
        CaseCauseBLL caseCauseBll = new CaseCauseBLL();
        DataTable dtNodesAll = new DataTable();
        public static TreeNode clicknode;//点击节点树后，保存该节点
        StringBuilder nodesTag;
        public StringBuilder nodesName = new StringBuilder();
        private static List<string> nodesTags = new List<string>();
        private static Dictionary<string, string> nodesLys = new Dictionary<string, string>();
        public string cCId;
        public string cCName;
        readonly Express_SourceBLL SourceBLL = new Express_SourceBLL();
        private int Type;

        public RuleShare(string ccName, string ccId,int type=0)
        {

            InitializeComponent();
            cCName = ccName;
            cCId = ccId;
            Type = type;
            if (type == 0)
            {
                this.Text = "规则共用";
            }else if (type == 0)
            {
                this.Text = "批量独立化";
            }
        }
        public string moveNodeState = string.Empty;
        public bool LevelShow { get; set; }

        private void MoveState_Load(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            dtNodesAll = caseCauseBll.GetAllChildNew("66666");
            var node1 = new TreeNode();
            node1.Text = "行政执法";
            node1.Tag = "66666";
            node1.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node1);
            NodeList.Add(node1);

            //var dt = trbll.NodeTree_Tree("");//第一层的树
            //var arrayDr = dt.Select("name='行政执法'");//找出“刑事罪名”的节点
            //foreach (var caseTreeNodeRode in arrayDr)
            //{
            //    var node = new TreeNode();
            //    node.Text = LdFormat.ObjectToString(caseTreeNodeRode[1]);
            //    node.Tag = caseTreeNodeRode[0];
            //    node.Name = LdFormat.ObjectToString(caseTreeNodeRode[2]);
            //    DataTable dtt = trbll.NodeTree_Tree(node.Tag.ToString());
            //    if (dtt.Rows.Count > 0)//节点有没有下级
            //    {
            //        //foreach (DataRow item in dtt.Rows)
            //        //{
            //        //    NodeList.Add(item["id"].ToString());
            //        //}
            //        node.Nodes.Add(new TreeNode());
            //    }
            //    treeView1.Nodes.Add(node);//父级节点添加节点
            //    NodeList.Add(node);
            //}
            treeView1.AfterExpand += TreeView_AfterExpand;
            treeView1.AfterCheck += TreeView1_AfterCheck;

            #region 共用节点树事件
            DataTable dtNodes = caseCauseBll.GetSysCaseDataByCCName(cCName);
            if (dtNodes != null && dtNodes.Rows.Count > 0)
            {
                QueryNode_Page(dtNodes);
            }

            #endregion

            #region 规则来源段
            DataTable dtExpressSource = SourceBLL.GetExpressSourceData(cCId);
            if (dtExpressSource != null && dtExpressSource.Rows.Count > 0)
            {
                cbxCheckLY.TreeView.Nodes.Clear();
                foreach (DataRow dr in dtExpressSource.Rows)
                {
                    var node = new TreeNode();
                    node.Text = dr["Source_Name"].ToString();
                    node.Tag = dr["CC_RegexInfoCode"].ToString();
                    cbxCheckLY.TreeView.Nodes.Add(node);
                }
            }
            cbxCheckLY.TreeView.AfterCheck += TreeView_AfterCheck;
            #endregion

        }

        private void TreeView_AfterCheck(object sender, TreeViewEventArgs e)
        {
            nodesLys.Clear();
            foreach (TreeNode item in cbxCheckLY.TreeView.Nodes)
            {
                if (item.Checked)
                {
                    if (!nodesLys.ContainsKey(item.Text.ToString()))
                    {
                        nodesLys.Add(item.Text.ToString(), item.Tag.ToString());
                    }
                }
            }
        }

        private void TreeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            nodesTags.Clear();
            GetCheckNode(); ;
        }

        public void GetCheckNode()
        {
            // nodesTag = new StringBuilder();
            TreeNode node = treeView1.Nodes[0];//得到treeview的根结点
            while (node.PrevNode != null)
            {
                node = node.PrevNode;
            }
            TraversNodes(node);//遍历根结点
            //return nodesTag.ToString();
        }

        /// <summary>
        /// 遍历方法
        /// </summary>
        /// <param name="parent"></param>
        private void TraversNodes(TreeNode parent)
        {
            TreeNode node = parent;
            if (node != null)
            {
                //if (node.Tag != null && node.Tag.ToString() == tag)
                //{
                if (node.Text != null && !string.IsNullOrEmpty(node.Text.ToString()) && node.Checked == true)
                {
                    //if (!nodesName.ToString().Contains(node.Text))
                    //{
                    //    string ss = node.Text.Replace(')', ' ');
                    //    nodesTag.AppendFormat("{0},", ss.Substring(ss.LastIndexOf('(') + 1));
                    //    string ss1 = node.Text.Replace('(', ' ');

                    //    nodesName.AppendFormat("{0},", node.Text.ToString());
                    //}
                    //else
                    //{
                    //    string ss = node.Text.Replace(')', ' ');
                    //    nodesTag.AppendFormat("{0},", ss.Substring(ss.LastIndexOf('(') + 1));
                    //}
                    if (!nodesTags.Contains(node.Tag.ToString()))
                    {
                        nodesTags.Add(node.Tag.ToString());
                    }
                }
                else if (node.Text != null && !string.IsNullOrEmpty(node.Text.ToString()) && node.Checked == false)
                {
                    //if (nodesName.ToString().Contains(node.Text))
                    //{
                    //    //string ss = node.Text.Replace(')', ' ');
                    //    //nodesTag.AppendFormat("{0},", ss.Substring(ss.LastIndexOf('(') + 1));
                    //    //string ss1 = node.Text.Replace('(', ' ');
                    //    nodesName.Replace(node.Text + ",", "");
                    //    //nodesName.AppendFormat("{0},", node.Text.ToString());
                    //}
                    //else
                    //{
                    //    string ss = node.Text.Replace(')', ' ');
                    //    nodesTag.AppendFormat("{0},", ss.Substring(ss.LastIndexOf('(') + 1));
                    //}
                    if (nodesTags.Contains(node.Tag.ToString()))
                    {
                        nodesTags.Remove(node.Tag.ToString());
                    }
                }

                if (node.FirstNode != null)//如果node节点还有子节点则进入遍历
                {
                    TraversNodes(node.FirstNode);
                }
                if (node.NextNode != null)//如果node节点后面有同级节点则进入遍历
                {
                    TraversNodes(node.NextNode);
                }
            }
        }

        private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (clicknode != null && clicknode.ForeColor != Color.Blue)
            {
                if (e.Node != null)
                {
                    if (clicknode.Text != e.Node.Text)
                    {
                        clicknode.ForeColor = Color.Black;
                    }
                }
            }
            if (e.Node != null)
            {
                clicknode = e.Node;//保存节点
                                   //根据ccid控制添加子节点、同级节点菜单显示             
                                   // if (clicknode.ForeColor != Color.Blue)
                                   //clicknode.ForeColor = Color.Red;
                                   ////    ColorCommonCase_Click(nul);
                                   //GetRightValue(e);//右侧信息展现
            }
        }

        private void TreeView_AfterExpand(object sender, TreeViewEventArgs e)
        {
            //if (e.Node.Nodes.Count == 0)
            //{
            e.Node.Nodes.Clear();
            CaseCauseTreeChild(e.Node);

        }

        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();// 父级ID
            var caseTreeNodeRode = GetNodes(pid);//父级ID的下级节点
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode();
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_Name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["CC_ID"];
                //node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
                if (GetNodes(node.Tag.ToString()).Rows.Count > 0)//节点有无下级
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);//父级节点添加节点
                TreeNode node1 = null;
                foreach (var node2 in NodeList)//遍历现在界面上的所有节点
                {
                    if (node2.Tag.ToString() == node.Tag.ToString())
                    {
                        node1 = node2;
                        break;
                    }
                }
                if (node1 != null)
                {
                    NodeList.Remove(node1);
                    NodeList.Add(node);//list用来查询
                }
                else
                {
                    NodeList.Add(node);
                }
            }
        }



        private DataTable GetNodes(string ccId)
        {
            if (dtNodesAll.Select(" CC_ParentID='" + ccId + "' ").Length > 0)
            {
                DataTable dt = dtNodesAll.Select(" CC_ParentID='" + ccId + "' ").CopyToDataTable();
                return dt;
            }
            else
            {
                return new DataTable();
            }
        }




        /// <summary>
        /// 定位到目标节点
        /// </summary>
        /// <param name="dt">查询返回结果集</param>
        /// <param name="showindex">第几条</param>
        private void QueryNode_Page(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    var NotePidArr = dr["AllParentId"].ToString().Split(',');
                    for (var i = 0; i < NotePidArr.Length; i++)
                    {
                        if (i != NotePidArr.Length - 1)
                        {
                            var Node = FindNode(NotePidArr[i]);
                            // && Node.IsExpanded == false
                            if (Node != null)
                            {
                                //if (Node.Tag.ToString() == "66666")
                                //{
                                //    CaseCauseTreeChild(Node);
                                //}

                                Node.Expand();//拖出所有父级节点
                            }
                        }
                        else  //最后一级节点为查找节点
                        {
                            // tVCaseCause.ExpandAll();
                            var node = FindNode(NotePidArr[i]);
                            node.Checked = true;
                            //tVCaseCause.SelectedNode = node;//定位          
                        }
                    }
                }
            }

        }

        /// <summary>
        /// 查找节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (var node in NodeList)//遍历现在界面上的所有节点
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;
            //return (TreeNode)NodeList[Nodeid];
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(txbNodes.Text.Trim()))
            //{
            //    MessageBox.Show("请在文本框输入文本后再试！");
            //    return;
            //}
            //else
            //{
            //    DataTable dtNodes = caseCauseBll.GetSysCaseDataByCCName(txbNodes.Text.Trim());
            //    if (dtNodes != null && dtNodes.Rows.Count > 0)
            //    {
            //        QueryNode_Page(dtNodes);
            //    }
            // }
        }

        /// <summary>
        /// 确定按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure_Click(object sender, EventArgs e)
        {
            int i = nodesTags.Count;
            int j = nodesLys.Count;
            if (Type == 0)
            {
                if (nodesTags.Count > 0)
                {
                    if (nodesLys.Count > 0)
                    {
                        this.Cursor = Cursors.WaitCursor;
                        if (dgvGZShare.Rows.Count > 0)
                        {
                            DataTable dtt = (DataTable)dgvGZShare.DataSource;
                            dtt.Rows.Clear();
                            dgvGZShare.DataSource = dtt;
                        }
                        StringBuilder sb = new StringBuilder();
                        foreach (string item in nodesTags)
                        {
                            sb.Append("'" + item + "',");
                        }
                        StringBuilder sbly = new StringBuilder();
                        foreach (string item in nodesLys.Keys)
                        {
                            bool res = SourceBLL.UpdateDataByCC_ID(nodesLys[item], sb.ToString().Substring(0, sb.Length - 1), item);
                            sbly.Append("'" + item + "',");
                        }
                        DataTable dt = SourceBLL.GetExpressData(sb.ToString().Substring(0, sb.Length - 1), sbly.ToString().Substring(0, sbly.Length - 1), cCName);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            dgvGZShare.DataSource = PublicMethod.AddDataTableNum(dt);
                        }
                        this.Cursor = Cursors.Default;
                    }
                    else
                    {
                        MessageBox.Show("请选择需要共用的规则来源段后再试！");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("请选择需要共用的节点后再试！");
                    return;
                }
            }
            else if (Type == 1)
            {
                if (nodesTags.Count > 0)
                {
                    if (nodesLys.Count > 0)
                    {
                        this.Cursor = Cursors.WaitCursor;
                        if (dgvGZShare.Rows.Count > 0)
                        {
                            DataTable dtt = (DataTable)dgvGZShare.DataSource;
                            dtt.Rows.Clear();
                            dgvGZShare.DataSource = dtt;
                        }
                        StringBuilder sb = new StringBuilder();
                        foreach (string item in nodesTags)
                        {
                            sb.Append("'" + item + "',");
                        }
                        StringBuilder sbly = new StringBuilder();
                        foreach (string item in nodesLys.Keys)
                        {
                            sbly.Append("'" + item + "',");
                        }
                        DataTable dt = SourceBLL.GetExpressData(sb.ToString().Substring(0, sb.Length - 1), sbly.ToString().Substring(0, sbly.Length - 1), cCName);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow item in dt.Rows)
                            {
                                string eiid = item["EI_ID"].ToString();
                                string esid = item["ES_ID"].ToString();
                                DLH(eiid, esid);
                            }
                            dt = SourceBLL.GetExpressDataPL(sb.ToString().Substring(0, sb.Length - 1), sbly.ToString().Substring(0, sbly.Length - 1));
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                dgvGZShare.DataSource = PublicMethod.AddDataTableNum(dt);
                            }
                        }
                        this.Cursor = Cursors.Default;
                    }
                    else
                    {
                        MessageBox.Show("请选择需要批量独立化的规则来源段后再试！");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("请选择需要批量独立化的节点后再试！");
                    return;
                }
            }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvGZShare_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex ==5)
                {
                    if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string esID = dgvGZShare.Rows[e.RowIndex].Cells["ES_ID"].Value.ToString();
                        bool res = SourceBLL.UpdateDataByES_ID(esID);
                        if (res)
                        {
                            dgvGZShare.Rows[e.RowIndex].Cells["eiid"].Value = "";
                            MessageBox.Show("删除成功!");
                        }
                        else
                        {
                            MessageBox.Show("删除失败!");
                        }
                    }
                }
            }
        }

        private void DLH(string eIID,string eSID)
        {
            NewIDBLL newid = new NewIDBLL();
            AboutRegexBLL regexbll = new AboutRegexBLL();

            #region  新建信息单元
            var nodeChild = new Model.Reg_InfoUnit();
            nodeChild.EI_Name =cCName;
            nodeChild.EN_ID = "EI_ID1507221438500001";
            nodeChild.EI_Remark = "";
            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
            regexbll.AddReg_InfoUnit(nodeChild);

            #endregion

            #region 修改来源与信息单元的对应关系
            var model = new SysExpressSource();
            model.ES_ID = eSID;
            model.CC_RegexInfoCode = nodeChild.EI_Code;
            SourceBLL.Update(model);
            #endregion

            #region 复制原正则和关系

            List<Reg_Regexs> regexs = regexbll.GetReg_RegexsByEiid(eIID);
            List<Model.Reg_InfoRegexRelation> regRelations = regexbll.GetRegexRelationByEiid(eIID);
            if (regexs.Count > 0 && regRelations.Count > 0)
            {
                for (int j = 0; j < regexs.Count; j++)
                {
                    regexs[j].ER_ID = newid.CreateID("Reg_Regexs");
                    regexbll.InsertReg_Regexs(regexs[j]);
                    regRelations[j].EI_ID = nodeChild.EI_ID;
                    regRelations[j].ER_ID = regexs[j].ER_ID;
                    regRelations[j].ERR_ID = newid.CreateID("Reg_InfoRegexRelation");
                    regexbll.InsertRegex(regRelations[j]);
                }
            }
            #endregion
        }
    }
}
